#include <iostream>
#include <string>
#include <vector>
#include <unistd.h>

namespace TheardMoudle
{
    
    class ThreadData
    {
    public:
        ThreadData(const std::string& name, pthread_mutex_t* mutex)
            :_name(name), _mutex(mutex), n(0)
        {}

        std::string _name;
        pthread_mutex_t* _mutex;
        size_t n;
    };

    typedef void (*func_t)(ThreadData*);

    class Thread
    {
    public:
        void Excute()
        {
            std::cout<<_name<<" is running "<<std::endl;
            _isrunning = 1;
            _func(_td);
            _isrunning = 0;
        }

        static void* ThreadRoutine(void* args)
        {
            Thread* self = static_cast<Thread*>(args);
            self->Excute();
            return nullptr;
        }

    public:
        
        Thread(std::string& name, func_t func, ThreadData* td)
            : _name(name), _func(func), _td(td)
        { }

        bool Start()
        {
            int n = pthread_create(&_tid, nullptr, ThreadRoutine, this);
            return n != 0;
        }

        void Stop()
        {
            if(_isrunning)
            {
                ::pthread_cancel(_tid);
                _isrunning = 0;
                std::cout<<_name<<" Stop"<<std::endl;
            }
        }

        void Join()
        {
            ::pthread_join(_tid, nullptr);
            std::cout<<_name<<" Join.    GetTickets: "<<_td->n<<std::endl;
        }



    private:
        pthread_t _tid;
        std::string _name;
        bool _isrunning;
        func_t _func;
        TheardMoudle::ThreadData* _td;
    };
}